package models

import (
	"database/sql"
	"fmt"
	"github.com/go-redis/redis/v8"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/setting"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"log"
	"time"
)

var db *gorm.DB
var sqlDB *sql.DB
var redisDB *redis.Client

func init() {
	var (
		err error
		 dbName, user, password, host, dbPort, timeZone, timeOut string
	)

	sec, err := setting.Cfg.GetSection("database")
	if err != nil {
		log.Fatal(2, "Fail to get sectio 'database': %v", err)
	}

	dbName = sec.Key("NAME").String()
	dbPort = sec.Key("PORT").String()
	user = sec.Key("USER").String()
	password = sec.Key("PASSWORD").String()
	host = sec.Key("HOST").String()
	timeZone = sec.Key("TIME_ZONE").String()
	timeOut = sec.Key("CONNECT_TIMEOUT").String()

	dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=%s connect_timeout=%s",
		host,
		user,
		password,
		dbName,
		dbPort,
		timeZone,
		timeOut,
	)
	db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Panic(err)

	}

	sqlDB, err = db.DB()
	if err != nil {
		log.Println(err)
	}

	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(time.Hour)

	// init redis
	if setting.RedisPassword == "" {
		redisDB = redis.NewClient(&redis.Options{
			Addr: setting.RedisHost + ":" + setting.RedisPort,
			//Password: setting.RedisPassword,
			DB: setting.RedisDB,
		})
	} else {
		redisDB = redis.NewClient(&redis.Options{
			Addr: setting.RedisHost + ":" + setting.RedisPort,
			Password: setting.RedisPassword,
			DB: setting.RedisDB,
		})
	}
}

func CloseDB() {
	defer sqlDB.Close()
	defer redisDB.Close()
}